
package com.bbh.plugin.single.privilege.demo.controller;

import com.bbh.plugin.single.privilege.core.entity.Account;
import com.bbh.plugin.single.privilege.core.service.OrganizationService;
import com.bbh.plugin.single.privilege.core.service.AccountService;
import com.bbh.common.domain.Message;
import com.bbh.common.domain.StatusType;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;


/**
 * Controller - 菜单
 * personal  个人中心
 *
 * @author KCSHOP Team
 * @version 3.0
 */
@Controller
@RequestMapping("/personal")
public class PersonalController extends BasicController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private OrganizationService organizationService;

    /**
     * 跳转密码修改页面
     *
     * @author bestgwd
     */
    @RequestMapping(value = VIEW_FILED + "/changePsw")
    public String toChangePasswordIndex(ModelMap model) {
        String loginName = getLoginName();
        if (StringUtils.isNotEmpty(loginName)) {
            Account account = new Account();
            account.setLoginName(getLoginName());
            account = accountService.selectOne(account);
            model.addAttribute("account", account);
            return "single/personal/changePsw";
        }
        return "single/common/error";
    }

    /**
     * 密码修改
     *
     * @author bestgwd
     */
    @RequestMapping(value = UPDATE_FILED + "/changePassword")
    public
    @ResponseBody
    Message changePassword(ModelMap model, @Valid Account account, String password, String newPassword) {
        Assert.isNull(account.getId(), "参数错误");
        if (StringUtils.isNotEmpty(password) && StringUtils.isNotEmpty(newPassword)) {
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            account = accountService.selectByPrimaryKey(account.getId());
            if (!password.equals(account.getPassword())) {
                return new Message(StatusType.ERROR.getKey(), "原密码错误");
            }
            newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
            account.setPassword(newPassword);
            accountService.updateByPrimaryKeySelective(account);
            return new Message(StatusType.SUCCESS.getKey(), "修改成功");
        }
        return new Message(StatusType.ERROR.getKey(), "修改失败");
    }

    /**
     * 跳转个人信息页面
     *
     * @author bestgwd
     */
    @RequestMapping(value = VIEW_FILED + "/information")
    public String toInformationIndex(ModelMap model) {
        String loginName = getLoginName();
        if (StringUtils.isNotEmpty(loginName)) {
            Account account = new Account();
            account.setLoginName(getLoginName());
            account = accountService.selectOne(account);
            model.addAttribute("account", account);
            return "single/personal/information";
        }
        return "single/common/error";
    }


    /**
     * update
     *
     * @return
     */
    @RequestMapping(VIEW_FILED + "/uploadImg")
    public
    @ResponseBody
    String update(@RequestParam("fileToUpload") MultipartFile file, HttpServletRequest request) throws Exception {
        String fileUploadPath = "/";
        if (file == null) {
            return null;
        }
        //取得当前上传文件的文件名称
        String fileName = file.getOriginalFilename();
        Long fileSize = file.getSize();
        if (fileSize.equals(512000)) {
            return new Message(StatusType.ERROR.getKey(), "上传文件在500KB以下").toString();
        }
        //验证文件格式
        Assert.hasText(fileName, "上传文件不能为空");
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
        if (!ArrayUtils.contains(new String[]{"jpg", "gif", "JPG", "GIF"}, ext)) {
            return "只允许上传jpg,gif格式的图片";
        }
        //定义上传路径,并且上传文件
        Calendar calendar = Calendar.getInstance();
        File folder = new File(fileUploadPath + File.separator + "images" + File.separator + "personal" + File.separator + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE));
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File localFile = new File(folder.getAbsolutePath() + File.separator + calendar.getTimeInMillis() + fileName);
        file.transferTo(localFile);
        //返回上传路径
        String path = localFile.getPath().replaceAll("\\\\", "/");
        return path.substring(path.indexOf("/boss/static"));
    }


    @RequestMapping(value = VIEW_FILED + "/toUploadImg", method = RequestMethod.GET)
    public String appList(ModelMap model, String idField, String textField, String exclude, String id) {
        Account account = new Account();
        if (StringUtils.isNotEmpty(id)) {
            account = accountService.selectByPrimaryKey(id);
        } else {
            String loginName = getLoginName();
            if (StringUtils.isNotEmpty(loginName)) {
                account.setLoginName(getLoginName());
                account = accountService.selectOne(account);
            } else return "common/error";

        }
        model.addAttribute("img", account.getPhoto());
        return "single/account/uploadImg";
    }

    /**
     * update
     *
     * @return
     */
    @RequestMapping(UPDATE_FILED + "/update")
    public
    @ResponseBody
    Message update(@Valid Account account) {
        Assert.notNull(account.getId(), "参数错误");
        Account modifyAccount = accountService.selectByPrimaryKey(account.getId());
        if (modifyAccount != null) {
            Date date = new Date();
            modifyAccount.setPhoto(account.getPhoto());
            modifyAccount.setModifyTime(date);
            modifyAccount.setDescription(account.getDescription());
            modifyAccount.setEmail(account.getEmail());
            modifyAccount.setPhone(account.getPhone());
            modifyAccount.setMobile(account.getMobile());
            accountService.updateByPrimaryKeySelective(modifyAccount);
            return new Message(StatusType.SUCCESS.getKey(), "更新成功");
        }
        return new Message(StatusType.ERROR.getKey(), "更新失败");
    }

    @RequestMapping(VIEW_FILED + "/uploadBase")
    public
    @ResponseBody
    String up(String imgStr, String fileName) throws Exception {//base64上传
        String fileUploadPath = "/boss/static";
        if (!StringUtils.isNotEmpty(imgStr)) {//判断是否为空
            return "上传文件不能为空";
        }
        String imgType = imgStr.substring(5, 14);
        if (!"image/png".equals(imgType)) {
            return "文件格式错误";
        }
        BASE64Decoder decoder = new BASE64Decoder();
        String img = imgStr.substring(22);
        File localFile = null;
        OutputStream out = null;
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(img);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //定义上传路径
            Calendar calendar = Calendar.getInstance();
            File folder = new File(fileUploadPath + File.separator + "images" + File.separator + "personal" + File.separator + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE));
            if (!folder.exists()) {
                folder.mkdirs();
            }
            localFile = new File(folder.getAbsolutePath() + File.separator + calendar.getTimeInMillis() + fileName);
            out = new FileOutputStream(localFile);
            out.write(b);
        } catch (Exception e) {
            throw e;
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
        String path = localFile.getPath().replaceAll("\\\\", "/");
        return path.substring(path.indexOf(fileUploadPath));
    }

    /**
     * 当前登录用户信息
     */
    @RequestMapping(VIEW_FILED + "/accountInformation")
    public
    @ResponseBody
    Account getAccountInfo() {
        Account account = new Account();
        account.setLoginName(getLoginName());
        account = accountService.selectOne(account);
        return account;
    }
}